Skip to content

New Components - tuya #16474

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

New Components - tuya #16474

wants to merge 4 commits into from

Conversation

michelle0927
Copy link
Collaborator

@michelle0927 michelle0927 commented Apr 29, 2025

Resolves #9874

Summary by CodeRabbit

  • New Features
    • Added actions to list Tuya homes and devices, and to send instructions to a Tuya device.
    • Introduced a source that emits events when a specified device parameter is updated.
  • Enhancements
    • Improved Tuya integration with dynamic option loading for users, homes, devices, and device functions.
    • Centralized and enhanced Tuya API client for more reliable interactions.
  • Chores
    • Updated package dependencies and version for the Tuya integration.
    • Added a test event for device state updates.

Copy link

vercel bot commented Apr 29, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview May 30, 2025 8:11pm
pipedream-docs ⬜️ Ignored (Inspect) May 30, 2025 8:11pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) May 30, 2025 8:11pm

Copy link
Contributor

coderabbitai bot commented Apr 29, 2025

Walkthrough

This update introduces a comprehensive Tuya integration, adding actions for listing homes and devices, sending device instructions, and a polling-based trigger for device parameter changes. The Tuya app is fully implemented with dynamic option loading and API methods. Supporting files include test data and updated dependencies.

Changes

File(s) Change Summary
components/tuya/actions/list-homes/list-homes.mjs Added "List Homes" action: retrieves homes for a user via Tuya API.
components/tuya/actions/list-devices/list-devices.mjs Added "List Devices" action: retrieves devices for a user or home via Tuya API.
components/tuya/actions/send-instructions-to-device/send-instructions-to-device.mjs Added "Send Instructions to Device" action: sends a command to a specified device.
components/tuya/sources/new-device-parameter-updated/new-device-parameter-updated.mjs Added polling source: emits events when a device parameter changes for a user/home.
components/tuya/sources/new-device-parameter-updated/test-event.mjs Added test event data for the new device parameter trigger.
components/tuya/tuya.app.mjs Implemented Tuya API client: dynamic prop loaders, API methods, authentication, and error handling.
components/tuya/package.json Updated version to 0.1.0; added dependencies for Tuya connector and Pipedream platform.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Action
    participant TuyaApp
    participant TuyaAPI

    User->>Action: Trigger action (e.g., List Devices)
    Action->>TuyaApp: Call method (e.g., listUserDevices or listHomeDevices)
    TuyaApp->>TuyaAPI: Make API request with credentials
    TuyaAPI-->>TuyaApp: Return device/home data
    TuyaApp-->>Action: Return data
    Action-->>User: Output result and summary
Loading
sequenceDiagram
    participant Source
    participant TuyaApp
    participant TuyaAPI
    participant EventDB

    Source->>TuyaApp: List devices (by home or user)
    TuyaApp->>TuyaAPI: API call for device list
    TuyaAPI-->>TuyaApp: Return device list
    TuyaApp-->>Source: Device list
    loop For each device
        Source->>TuyaApp: Get device status
        TuyaApp->>TuyaAPI: API call for device status
        TuyaAPI-->>TuyaApp: Return status
        TuyaApp-->>Source: Status data
        Source->>EventDB: Compare with cached parameter
        alt Changed
            Source->>EventDB: Update cache
            Source-->>User: Emit event
        end
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Tuya Cloud integration: authentication, API client, error handling (#9874)
Action: Get a list of "Homes" associated with a user (#9874)
Action: Get a list of devices (all or by home) (#9874)
Trigger: Fire when a particular device event/parameter changes (#9874)
Action: Set a device parameter (e.g., switch ON) (#9874)

Poem

In the warren of code, new features arise,
Tuya’s devices now dance before rabbit eyes.
Homes are listed, switches obey,
Device events hop in without delay.
🐇 With every API call, our burrow grows bright—
Smart homes and rabbits, connected just right!

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

components/tuya/sources/new-device-parameter-updated/test-event.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:799:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:723:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:706:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:307:38)
at #link (node:internal/modules/esm/module_job:170:49)

components/tuya/tuya.app.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:799:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:723:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:706:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:307:38)
at #link (node:internal/modules/esm/module_job:170:49)

components/tuya/sources/new-device-parameter-updated/new-device-parameter-updated.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:799:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:723:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:706:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:307:38)
at #link (node:internal/modules/esm/module_job:170:49)

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (3)
components/tuya/actions/list-devices/list-devices.mjs (2)

4-8: Update description to reflect dual functionality.

The description only mentions listing devices associated with a home, but the action actually supports listing devices for both a home and a user.

-  description: "Get a list of devices associated with a home. [See the documentation](https://developer.tuya.com/en/docs/cloud/d7ee73aadb?id=Kawfjer0wkt2a)",
+  description: "Get a list of devices associated with a home or user. [See the documentation](https://developer.tuya.com/en/docs/cloud/d7ee73aadb?id=Kawfjer0wkt2a)",

36-40: Improve handling of empty results.

The code only sets a summary when devices are found, but should also provide feedback when no devices are found.

    if (response?.result?.length) {
      $.export("$summary", `Found ${response.result.length} device${response.result.length === 1
        ? ""
        : "s"}`);
+   } else {
+     $.export("$summary", "No devices found");
    }
components/tuya/tuya.app.mjs (1)

90-94: Pass data only for non-GET requests

Some HTTP clients treat a body on GET as invalid.
A quick guard avoids surprises:

 const response = await this._getClient().request({
   method,
   path,
-  body: data,
+  ...(method === "GET" ? {} : { body: data }),
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 556dc7b and 912d22a.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • components/tuya/actions/list-devices/list-devices.mjs (1 hunks)
  • components/tuya/actions/list-homes/list-homes.mjs (1 hunks)
  • components/tuya/actions/send-instructions-to-device/send-instructions-to-device.mjs (1 hunks)
  • components/tuya/package.json (2 hunks)
  • components/tuya/sources/new-device-activated/new-device-activated.mjs (1 hunks)
  • components/tuya/tuya.app.mjs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: pnpm publish
  • GitHub Check: Verify TypeScript components
  • GitHub Check: Lint Code Base
  • GitHub Check: Publish TypeScript components
🔇 Additional comments (7)
components/tuya/package.json (2)

3-3: Version increment looks appropriate.

The version update from 0.0.1 to 0.1.0 follows semantic versioning principles, correctly indicating significant new functionality being added to the package.


15-18:

✅ Verification successful

Dependencies section looks good, but verify Tuya connector version.

The dependencies are properly structured with appropriate version ranges. Make sure that "@tuya/tuya-connector-nodejs" v2.1.2 is the latest stable version to ensure access to all necessary API features and security fixes.


🏁 Script executed:

#!/bin/bash
# Check if there are newer versions of the Tuya connector package
npm view @tuya/tuya-connector-nodejs versions --json | jq 'if type=="array" then .[-5:] else . end'

# Check for any security advisories
npm audit @tuya/tuya-connector-nodejs || echo "No direct vulnerability info available"

Length of output: 2468


Confirmed Tuya connector version is up to date

Verified that @tuya/[email protected] is the latest stable release and there are no direct vulnerabilities reported against it. The dependencies section is good to merge.

components/tuya/actions/send-instructions-to-device/send-instructions-to-device.mjs (1)

3-69: Well-structured action component with good organization.

The component properly implements the Pipedream action architecture with appropriate props, dynamic loading, and API interaction.

components/tuya/sources/new-device-activated/new-device-activated.mjs (2)

4-43: Well-implemented polling source with proper deduplication and state management.

The component correctly implements a polling-based source with dedupe settings, database persistence, and appropriate prop definitions.


38-50:

✅ Verification successful

Verify timestamp format and comparison.

The code assumes device.active_time and the stored lastTs use the same format and are directly comparable. If these are in different formats or time zones, it could cause issues with event detection.

Verify that the timestamps are in the same format and are correctly comparable:


🏁 Script executed:

#!/bin/bash
# Find and display examples of the active_time format from the Tuya API documentation
echo "Searching for active_time in Tuya API docs..."
rg -A 2 -B 2 "active_time" --json

Length of output: 4335


🏁 Script executed:

#!/bin/bash
# Display the beginning of the source file to inspect how `devices` and `active_time` are obtained
sed -n '1,120p' components/tuya/sources/new-device-activated/new-device-activated.mjs

Length of output: 1913


Active_time is a numeric epoch timestamp and directly comparable

I’ve confirmed that device.active_time is returned by the Tuya Cloud API as a UNIX‐epoch number (seconds since 1970), and lastTs is stored and retrieved as the same numeric value via this.db. The direct >= and Math.max comparisons are therefore safe—no format or timezone conversions are needed.

components/tuya/tuya.app.mjs (1)

78-84: Consider memoising the Tuya client

_getClient() instantiates a new TuyaContext on every request.
If the SDK performs auth handshakes or creates sockets, this can be wasteful.
Storing a single instance (e.g. in this._client) would cut overhead.

[ suggest_optional_refactor ]

components/tuya/actions/list-homes/list-homes.mjs (1)

18-27: Action depends on fixed helpers — verify once _makeRequest is returned

With the bug in _makeRequest corrected, ensure this action still handles
cases where response.result is undefined (e.g. no homes found).

-const response = await this.tuya.listHomes({ userId: this.userId });
-if (response?.result?.length) {
-  $.export("$summary", `Found ${response.result.length} home${response.result.length === 1 ? "" : "s"}`);
-}
-return response;
+const response = await this.tuya.listHomes({ userId: this.userId });
+const homes = response?.result ?? [];
+$.export("$summary", `Found ${homes.length} home${homes.length === 1 ? "" : "s"}`);
+return response;

This keeps the summary logic robust even when the API legitimately returns an empty array.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (3)
components/tuya/tuya.app.mjs (3)

85-99: ⚠️ Potential issue

_makeRequest() still returns undefined on the happy-path

This was flagged in the previous review but hasn’t been addressed.
Because the function never returns a value when the request is successful, every wrapper (listHomes, listUserDevices, …) resolves to undefined, breaking dynamic props and any consumer relying on the data.

       if (!response.success) {
         console.log(response);
         throw new ConfigurationError(`${response.msg}`);
       }
+      // Return the full response (or `response.result` if callers only need the
+      // payload) so that helpers receive actual data
+      return response;

12-19: ⚠️ Potential issue

Unsafe nested-destructuring can crash option loading

If listUsers() fails or returns an unexpected payload,
const { result: { list } } = … throws a TypeError, preventing the UI from loading the prop options.

-const { result: { list } } = await this.listUsers();
-return list?.map(({ user_id: value, user_name: label }) => ({ label, value })) || [];
+const { result } = await this.listUsers();
+const list = result?.list ?? [];
+return list.map(({ user_id: value, user_name: label }) => ({ label, value }));

123-130: 🛠️ Refactor suggestion

sendInstructionsToDevice() still accepts arbitrary data, no validation

The Tuya API expects a JSON body { "commands": [...] }.
Allowing any payload without validation can lead to silent no-ops or malformed requests.
Please validate the input and make the signature clearer.

-sendInstructionsToDevice({
-  deviceId, data,
-}) {
-  return this._makeRequest({
-    method: "POST",
-    path: `/v1.0/devices/${deviceId}/commands`,
-    data,
-  });
+sendInstructionsToDevice({ deviceId, commands }) {
+  if (!Array.isArray(commands) || !commands.length) {
+    throw new ConfigurationError("`commands` must be a non-empty array");
+  }
+  return this._makeRequest({
+    method: "POST",
+    path: `/v1.0/devices/${deviceId}/commands`,
+    data: { commands },
+  });
 }
🧹 Nitpick comments (1)
components/tuya/tuya.app.mjs (1)

78-84: Consider caching the Tuya client instance

_getClient() instantiates TuyaContext on every call, adding unnecessary overhead and preventing connection pooling.
Storing the client in this after first creation is a low-effort optimisation.

-_getClient() {
-  return new TuyaContext({
-    baseUrl: this.$auth.base_url,
-    accessKey: this.$auth.client_id,
-    secretKey: this.$auth.client_secret,
-  });
+_getClient() {
+  if (!this._client) {
+    this._client = new TuyaContext({
+      baseUrl: this.$auth.base_url,
+      accessKey: this.$auth.client_id,
+      secretKey: this.$auth.client_secret,
+    });
+  }
+  return this._client;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 912d22a and 3759c3b.

📒 Files selected for processing (1)
  • components/tuya/tuya.app.mjs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: pnpm publish
  • GitHub Check: Verify TypeScript components
  • GitHub Check: Publish TypeScript components

lcaresia
lcaresia previously approved these changes May 2, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
components/tuya/sources/new-device-parameter-updated/new-device-parameter-updated.mjs (1)

50-54: Add defensive checks for device status structure.

The method should handle cases where the device object might not have the expected structure.

    getCurrentValue(device) {
+     if (!device?.status || !Array.isArray(device.status)) {
+       return undefined;
+     }
      const { status } = device;
      const relevantStatus = status.find(({ code }) => code === this.deviceParameter);
      return relevantStatus?.value;
    },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3759c3b and ef8c964.

📒 Files selected for processing (3)
  • components/tuya/sources/new-device-parameter-updated/new-device-parameter-updated.mjs (1 hunks)
  • components/tuya/sources/new-device-parameter-updated/test-event.mjs (1 hunks)
  • components/tuya/tuya.app.mjs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • components/tuya/sources/new-device-parameter-updated/test-event.mjs
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Publish TypeScript components
  • GitHub Check: pnpm publish
  • GitHub Check: Verify TypeScript components
  • GitHub Check: Lint Code Base
🔇 Additional comments (2)
components/tuya/tuya.app.mjs (2)

76-91: Good fix for the return statement!

The _makeRequest method now correctly returns the response object, which resolves the previous issue where all helper methods would resolve to undefined.


112-120: Good fix for the command payload!

The sendInstructionsToDevice method now correctly accepts and passes the data parameter containing the commands to the API, addressing the previous issue where commands were ignored.

@michelle0927
Copy link
Collaborator Author

@vunguyenhung I think there may be multilple ways to create user IDs. The IDs Sergio and I were able to create can be seen in the UI here: Cloud -> Project Management -> Open Project -> Devices -> Link App Account.

Screenshot 2025-05-30 at 4 14 40 PM

@michelle0927
Copy link
Collaborator Author

/approve

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Smarlife / Tuya Cloud Services
2 participants